package com.fenrirtec.aepp.manage.api;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.fenrirtec.aepp.common.dto.TenderDetailDto;
import com.fenrirtec.aepp.common.service.TenderService;
import com.fenrirtec.aepp.common.service.impl.TenderServiceImpl;
import com.fenrirtec.aepp.common.support.JSONActionSupport;
import com.fenrirtec.core.definition.BaseDefinition.API;
import com.fenrirtec.core.definition.BaseDefinition.API.Common;
import com.fenrirtec.core.exception.DatabaseException;
import com.fenrirtec.core.exception.UnexpectedException;

public class TenderStatusChangeAPI extends JSONActionSupport{
	
	private static final long serialVersionUID = 1L;

	private static final Logger logger = LoggerFactory.getLogger(TenderStatusChangeAPI.class);

	public TenderStatusChangeAPI() {
	}

	private String param;

	public String getParam() {
		return this.param;
	}

	public void setParam(String param) {
		this.param = param;
	}

	@Override
	protected List<ErrorInfo> doValidate() {
	    JSONObject jsonObj = JSONObject.parseObject(this.param);
        Integer tenderId = jsonObj.getInteger("tender_id");
        Integer status = jsonObj.getInteger("status");
        TenderService tenderService = new TenderServiceImpl();
        TenderDetailDto tenderDetailDto = tenderService.findDetail(tenderId);
        List<ErrorInfo> errorList = null;
        if (tenderDetailDto == null) {
            errorList = new ArrayList<ErrorInfo>();
            ErrorInfo error = new ErrorInfo("招标信息不存在，请刷新数据后重试！", ErrorType.ERROR);
            errorList.add(error);
        } else if (tenderDetailDto.getStatus().intValue() >= status.intValue()) {
            errorList = new ArrayList<ErrorInfo>();
            ErrorInfo error = new ErrorInfo("招标信息状态已变更，请刷新数据后重试！", ErrorType.ERROR);
            errorList.add(error);
        }
        
        return errorList;
	}
	
	@Override
	protected JSONObject doExecute() {
		
	    TenderService tenderService = new TenderServiceImpl();
	    Boolean result = false;
		
		try {
			JSONObject jsonObj = JSONObject.parseObject(this.param);
			Integer tenderId = jsonObj.getInteger("tender_id");
			Integer status = jsonObj.getInteger("status");
			result = tenderService.changeStatus(tenderId, status, getUserInfo().getLoginName());
		} catch (DatabaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error("database error occurred.", e);
			}
			throw new JSONActionStatusException(API.Common.Status.DB_ERROR, e);
		} catch (UnexpectedException e) {
			if (logger.isErrorEnabled()) {
				logger.error("unexpected error occurred.", e);
			}
			throw new JSONActionStatusException(API.Common.Status.DB_ERROR, e);
		} 

		JSONObject root = new JSONObject();
		root.put(Common.Response.RESULT, result);
		return root;
	}	
}
